package com.atguigu.dga.util;

import org.antlr.runtime.tree.Tree;
import org.apache.hadoop.hive.ql.lib.DefaultGraphWalker;
import org.apache.hadoop.hive.ql.lib.Dispatcher;
import org.apache.hadoop.hive.ql.lib.Node;
import org.apache.hadoop.hive.ql.parse.*;

import java.util.Collections;
import java.util.Stack;

public class SqlParser {


    public  static void  parse(String sql , Dispatcher myDispatcher) throws  Exception {
        // 1  创建一个sql解析工具
        ParseDriver parseDriver = new ParseDriver();

        // 2 用sql解析工具分析sql 生成语法树
        ASTNode astNode = parseDriver.parse(sql);

        // 3 把语法树根节点剪除
        ASTNode startNode =(ASTNode) astNode.getChild(0);

        // 4 创建遍历器 同时把节点处理器放入遍历器
        DefaultGraphWalker graphWalker = new DefaultGraphWalker(myDispatcher);

        // 5 遍历器进行节点遍历
        graphWalker.startWalking(  Collections.singletonList(startNode)  ,null);


    }

    public static void main(String[] args) throws Exception {
         String  sql = " select  oi.id ,oi.total_amount ,od.sku_id  from gmall.order_info oi , order_detail od where oi.id=od.order_id";
         String  sql2 = " select  oi.id ,oi.total_amount ,oi.sku_id  from order_info oi ";
        JoinDispatcher joinDispatcher = new JoinDispatcher();
        parse(sql2,joinDispatcher);
        System.out.println("joinDispatcher.hasJoin = " + joinDispatcher.hasJoin);

    }

    static class JoinDispatcher implements Dispatcher{

        boolean hasJoin=false;

        @Override
        public Object dispatch(Node nd, Stack<Node> stack, Object... nodeOutputs) throws SemanticException {
            ASTNode astNode = (ASTNode) nd;
            if(astNode.getType()== HiveParser.TOK_JOIN){
                hasJoin=true;
            }
            System.out.println(astNode.getText());

            return null;
        }
    }

}
